#!/bin/bash
# 使用镜像加速github
# Author: LiDong (cnlidong@live.cn)
# Date: 2022-11-10

PERFIX="https://ghproxy.com/"

VERSION="1.0.0"

# 获取环境变量 PGIT_PREFIX, 如果没有设置则使用默认值
if [ -n "$PGIT_PREFIX" ]; then
    PERFIX=$PGIT_PREFIX
fi



# 如果没有参数，则显示帮助
if [ $# -eq 0 ]; then
    # 获取脚本所在目录
    DIR=$(
        cd $(dirname $0)
        pwd
    )
    echo "------------------------------------------------------------"
    echo "pgit installed in $DIR"
    echo "Current version: $VERSION"
    echo "Current mirror: $PERFIX"
    echo "Usage: pgit install|clone|wget|crul|... [args]"
    echo "  install: install pgit"
    echo "  clone: clone github repo"
    echo "  wget: wget github repo or file"
    echo "Example:"
    echo "  ./pgit install"
    echo "  pgit clone https://github.com/cool-team-official/cool-admin-vue.git"
    echo "  pgit wget -O cool-admin-codespace.zip https://github.com/cool-team-official/cool-admin-codespace/archive/refs/heads/local.zip"
    echo "------------------------------------------------------------"
    exit 0
fi

# 如果第一个参数为 install 则安装
if [ "$1" == "install" ]; then
    echo "安装中..."
    cp $0 /usr/local/bin/pgit
    chmod +x /usr/local/bin/pgit
    echo "安装完成！"
    exit 0
fi

# 如果第一个参数为 clone 则 clone
if [ "$1" == "clone" ]; then
    # 获取所有参数
    args=("$@")
    # 获取参数个数
    length=$#
    # 遍历参数
    for ((i = 0; i < $length; i++)); do
        # 获取参数
        arg=${args[$i]}
        # 判断参数是否是github仓库地址
        if [[ $arg == *"github.com/"* ]]; then
            # 替换参数, 使用镜像地址
            args[$i]=${PERFIX}$arg
        fi
    done

    # Replace URL and call git
    echo "Using mirror: $PERFIX ..."
    echo "git ${args[@]}"
    git ${args[@]}
fi

# 如果第一个参数为 wget 则 wget
if [ "$1" == "wget" ]; then
    # 获取所有参数
    args=("$@")
    # 获取参数个数
    length=$#
    # 遍历参数
    for ((i = 0; i < $length; i++)); do
        # 获取参数
        arg=${args[$i]}
        # 判断参数是否是github仓库地址 或者是文件地址
        if [[ $arg == *"github.com/"* ]] || [[ $arg == *"raw.githubusercontent.com/"* ]]; then
            # 替换参数, 使用镜像地址
            args[$i]=${PERFIX}$arg
        fi
    done
    # 移除第一个参数
    unset args[0]
    # Replace URL and call git
    echo "Using mirror: $PERFIX ..."
    echo "wget ${args[@]}"
    wget ${args[@]}
fi

# 如果第一个参数为 curl 则 curl
if [ "$1" == "curl" ]; then
    # 获取所有参数
    args=("$@")
    # 获取参数个数
    length=$#
    # 遍历参数
    for ((i = 0; i < $length; i++)); do
        # 获取参数
        arg=${args[$i]}
        # 判断参数是否是github仓库地址 或者是文件地址
        if [[ $arg == *"github.com/"* ]] || [[ $arg == *"raw.githubusercontent.com/"* ]]; then
            # 替换参数, 使用镜像地址
            args[$i]=${PERFIX}$arg
        fi
    done
    # 移除第一个参数
    unset args[0]
    # Replace URL and call git
    echo "Using mirror: $PERFIX ..."
    echo "curl ${args[@]}"
    curl ${args[@]}
fi